/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Group;
import edu.cmu.fithub.db.bean.GroupMembers;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.formbeans.LoginForm;

public class SearchGroupAction extends Action {

	private FormBeanFactory<LoginForm> formFactory = FormBeanFactory
			.getInstance(LoginForm.class);

	public SearchGroupAction() {
	}

	public String getName() {
		return "searchGroup.do";
	}

	public String perform(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		String groupName = (String) request.getParameter("searchGroup");
		Session dbSession = DBHelper.getSessionFactory().openSession();
		List<Group> allGroups = dbSession.createCriteria(Group.class)
				.add(Restrictions.ilike("groupName", "%" + groupName + "%"))
				.add(Restrictions.ne("adminId", user.getUserId()))
				.add(Restrictions.eq("groupType", "open")).list();
		List<GroupMembers> subscribedGroups = dbSession
				.createCriteria(GroupMembers.class)
				.add(Restrictions.eq("userId", user.getUserId())).list();

		List<Integer> subscribedGroupsId = new ArrayList<Integer>();

		for (int i = 0; i < subscribedGroups.size(); i++) {
			subscribedGroupsId.add(subscribedGroups.get(i).getGroup()
					.getGroupId());
		}
		for (int i = 0; i < allGroups.size(); i++) {
			if (subscribedGroupsId.contains(allGroups.get(i).getGroupId())) {
				allGroups.remove(i);
			}
		}
		Group[] searchGroups = new Group[allGroups.size()];
		searchGroups = allGroups.toArray(searchGroups);
		request.setAttribute("searchGroups", searchGroups);
		return "showGroups.do";
	}
}
